﻿/******************************************************************************
 * Copyright (C) 2015  671643387@qq.com
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 *****************************************************************************/

#include "Shared/Crypto/Hmac.h"
#include "Shared/Crypto/BigNumber.h"


namespace Shared {
namespace Crypto {

    HmacHash::HmacHash()
    {
        std::uint8_t temp[SEED_KEY_SIZE] = { 0x38, 0xA7, 0x83, 0x15, 0xF8, 0x92, 
            0x25, 0x30, 0x71, 0x98, 0x67, 0xB1, 0x8C, 0x4, 0xE2, 0xAA };
        memcpy(&_key, &temp, SEED_KEY_SIZE);
        HMAC_CTX_init(&_ctx);
        HMAC_Init_ex(&_ctx, &_key, SEED_KEY_SIZE, EVP_sha1(), NULL);
    }

    HmacHash::~HmacHash()
    {
        memset(&_key, 0x00, SEED_KEY_SIZE);
        HMAC_CTX_cleanup(&_ctx);
    }

    void HmacHash::updateBigNumber(BigNumber* bn)
    {
        updateData(bn->asByteArray(), bn->getNumBytes());
    }

    void HmacHash::updateData(const ::std::uint8_t* data, int size)
    {
        HMAC_Update(&_ctx, data, size);
    }

    void HmacHash::initialize()
    {
        HMAC_Init_ex(&_ctx, &_key, SEED_KEY_SIZE, EVP_sha1(), NULL);
    }

    void HmacHash::finalize()
    {
        std::uint32_t size = 0;
        HMAC_Final(&_ctx, _digest, &size);
        SHARED_ASSERT(size == SHA_DIGEST_LENGTH);
    }

}}